package com.ruoyi.common.utils

import com.ruoyi.common.constant.Constants
import com.ruoyi.common.core.text.Convert.toBool
import com.ruoyi.common.core.text.Convert.toInt
import com.ruoyi.common.core.text.Convert.toStr
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*
import javax.servlet.ServletRequest
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

/**
 * 客户端工具类
 *
 * @author ruoyi
 */
object ServletUtils {
    /**
     * 获取String参数
     */
    @JvmStatic
    fun getParameter(name: String?): String? {
        return request.getParameter(name)
    }

    /**
     * 获取String参数
     */
    fun getParameter(name: String?, defaultValue: String?): String? {
        return toStr(request.getParameter(name), defaultValue)
    }

    /**
     * 获取Integer参数
     */
    fun getParameterToInt(name: String?): Int? {
        return toInt(request.getParameter(name))
    }

    /**
     * 获取Integer参数
     */
    fun getParameterToInt(name: String?, defaultValue: Int?): Int? {
        return toInt(request.getParameter(name), defaultValue)
    }

    /**
     * 获取Boolean参数
     */
    @JvmStatic
    fun getParameterToBool(name: String?): Boolean? {
        return toBool(request.getParameter(name))
    }

    /**
     * 获取Boolean参数
     */
    fun getParameterToBool(name: String?, defaultValue: Boolean?): Boolean? {
        return toBool(request.getParameter(name), defaultValue)
    }

    /**
     * 获得所有请求参数
     *
     * @param request 请求对象[ServletRequest]
     * @return Map
     */
    fun getParams(request: ServletRequest): Map<String, Array<String>> {
        val map = request.parameterMap
        return Collections.unmodifiableMap(map)
    }

    /**
     * 获得所有请求参数
     *
     * @param request 请求对象[ServletRequest]
     * @return Map
     */
    @JvmStatic
    fun getParamMap(request: ServletRequest): Map<String, String> {
        val params: MutableMap<String, String> = mutableMapOf()
        for ((key, value) in getParams(request)) {
            params[key] = org.apache.commons.lang3.StringUtils.join(value, ",")
        }
        return params
    }

    @JvmStatic
    val request: HttpServletRequest
        /**
         * 获取request
         */
        get() = requestAttributes.request
    val response: HttpServletResponse?
        /**
         * 获取response
         */
        get() = requestAttributes.response
    val session: HttpSession
        /**
         * 获取session
         */
        get() = request.session
    val requestAttributes: ServletRequestAttributes
        get() {
            val attributes = RequestContextHolder.getRequestAttributes()
            return attributes as ServletRequestAttributes
        }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     */
    @JvmStatic
    fun renderString(response: HttpServletResponse, string: String?) {
        try {
            response.status = 200
            response.contentType = "application/json"
            response.characterEncoding = "utf-8"
            response.writer.print(string)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param request
     */
    fun isAjaxRequest(request: HttpServletRequest): Boolean {
        val accept = request.getHeader("accept")
        if (accept != null && accept.contains("application/json")) {
            return true
        }
        val xRequestedWith = request.getHeader("X-Requested-With")
        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
            return true
        }
        val uri = request.requestURI
        if (MyStringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
            return true
        }
        val ajax = request.getParameter("__ajax")
        return MyStringUtils.inStringIgnoreCase(ajax, "json", "xml")
    }

    /**
     * 内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    fun urlEncode(str: String?): String {
        return try {
            URLEncoder.encode(str, Constants.UTF8)
        } catch (e: UnsupportedEncodingException) {
            org.apache.commons.lang3.StringUtils.EMPTY
        }
    }

    /**
     * 内容解码
     *
     * @param str 内容
     * @return 解码后的内容
     */
    fun urlDecode(str: String?): String {
        return try {
            URLDecoder.decode(str, Constants.UTF8)
        } catch (e: UnsupportedEncodingException) {
            org.apache.commons.lang3.StringUtils.EMPTY
        }
    }
}
